package dav

import (
	"net/http"
	"net/url"
	"tosServer/internal/model"
	"tosServer/internal/pkg/db"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"golang.org/x/net/webdav"
)

var memLS = webdav.NewMemLS()

func (d *Dav) Dir(c *gin.Context) {
	user, exist := c.Get("user")
	if !exist {
		c.Header("WWW-Authenticate", `Basic realm="WebDAV"`)
		c.AbortWithStatus(http.StatusUnauthorized)
	}

	var davUser model.DavUser
	davUser = user.(model.DavUser)

	handler := &webdav.Handler{
		Prefix:     viper.Get("dav.prefix").(string),
		FileSystem: webdav.Dir(viper.Get("dav.root_dir").(string) + davUser.DavUserRole.Path),
		LockSystem: memLS,
		Logger: func(r *http.Request, err error) {
			go func() {
				davLog := new(model.DavLog)
				davLog.UserID = davUser.ID
				if err != nil {
					davLog.Type = 0
					davLog.Reason = err.Error()
				} else {
					davLog.Type = 1
				}

				davLog.OriginalPath = r.URL.Path
				destination := r.Header.Get("Destination")
				if destination != "" {
					urlParse, err := url.Parse(destination)
					if err == nil {
						davLog.OriginalPath = urlParse.Path
					}
				}

				davLog.Method = r.Method
				davLog.Path = r.URL.Path
				davLog.Filesize = r.ContentLength
				db.Db().Table(model.TableNameDavLog).Create(davLog)
			}()
		},
	}

	handler.ServeHTTP(c.Writer, c.Request)
}
